package ar.edu.itba.pod.legajo47573;

import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import ar.edu.itba.balance.api.AgentsBalancer;
import ar.edu.itba.balance.api.AgentsTransfer;
import ar.edu.itba.event.RemoteEventDispatcher;
import ar.edu.itba.node.Node;
import ar.edu.itba.node.NodeInformation;
import ar.edu.itba.node.api.ClusterAdministration;
import ar.edu.itba.node.api.StatisticReports;

public class Registries {

	public static Remote getRemoteObject(MyNode sourceNode, NodeInformation askedNode, String registryName){
		try {
			Registry reg = LocateRegistry.getRegistry(askedNode.host(), askedNode.port());
			if(registryName.equals(Node.DISTRIBUTED_EVENT_DISPATCHER))
				return (RemoteEventDispatcher)reg.lookup(registryName);
			else if(registryName.equals(Node.CLUSTER_COMUNICATION)){
				return (ClusterAdministration)reg.lookup(registryName);
			}
			else if(registryName.equals(Node.AGENTS_TRANSFER)){
				return (AgentsTransfer)reg.lookup(registryName);
			}
			else if(registryName.equals(Node.AGENTS_BALANCER)){
				return (AgentsBalancer)reg.lookup(registryName);
			}
			else if(registryName.equals(Node.STATISTIC_REPORTS)){
				return (StatisticReports)reg.lookup(registryName);
			}
		} catch (Exception e) {
			try{
				System.out.println("ME VOY A DESCONECTAR");
				sourceNode.getCluster().disconnectFromGroup(askedNode);
			} catch(Exception e1){
				System.out.println("Error al desconectar el nodo");
				e.printStackTrace();
			}
		}
		return null;
	}

}